package org.zezs.sync.mongo.config.es;

import com.alibaba.fastjson.JSONArray;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.cardinality.InternalCardinality;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zezs.sync.mongo.Constants;
import org.zezs.sync.mongo.utils.InputStreamUtil;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class EsUtil {
    static Logger logger = LoggerFactory.getLogger(EsUtil.class);
    public static Map<String, EsConfig> map = new HashMap<>();

    public static TransportClient getClient(String source) {
        EsConfig mongoEnt = map.get(source);
        if (mongoEnt == null) {
            return null;
        }
        return mongoEnt.getClient();
    }

    public static void init() {
        try {
            byte[] copyToByteArray = InputStreamUtil.readAll(Constants.esfile);
            List<EsConfig> parse = JSONArray.parseArray(new String(copyToByteArray, "utf-8"), EsConfig.class);
            for (int i = 0; i < parse.size(); i++) {
                EsConfig mongoEnt = parse.get(i);
                if (mongoEnt.isUse()) {
                    TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(mongoEnt.getIp()), mongoEnt.getPort());
                    Settings build = Settings.builder().put("cluster.name", mongoEnt.getCluster()).build();
                    PreBuiltTransportClient preBuiltTransportClient = new PreBuiltTransportClient(build);
                    preBuiltTransportClient.addTransportAddress(transportAddress);
                    TransportClient client = preBuiltTransportClient;
                    mongoEnt.setClient(client);
                    map.put(mongoEnt.getName(), mongoEnt);
                }

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        EsUtil.init();
        TransportClient client = EsUtil.getClient("152local");
        QueryBuilder query = QueryBuilders.boolQuery();
        List<QueryBuilder> must = ((BoolQueryBuilder) query).must();
        must.add(QueryBuilders.queryStringQuery( "13951999435 421121198906234018 340521199303012032 13855531406 18761613273 342423198706092596 13357838236 342222199108106449  15155368112 422101198208280821 15996249633 18061665848").field("content"));
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch("webservicelog_xhpro")
                .setTypes("webservicelog").setSize(2000).
                        setScroll(TimeValue.timeValueMinutes(1)).setFetchSource(new String[]{"visitDate","data"}, null);
        searchRequestBuilder.setQuery(query);
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();

        System.out.println("总数" + searchResponse.getHits().getTotalHits() );

        SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        // Always use the UTC time zone as we are using a constant trailing "Z" here.
        datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy'_webServiceLog_'MM");
        SearchHit[] hits = searchResponse.getHits().getHits();
        List<String> list=new ArrayList<>();
        for (SearchHit searchHit: hits) {
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            try {
                list.add(dateFormat.format(datetimeFormat.parse(sourceAsMap.get("visitDate").toString()))+" "+((Map)sourceAsMap.get("data")).get("serialNumber"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        list.sort(String::compareTo);
        list.forEach(s -> {
            System.out.println(s);
        });

    }

}
